package com.gupao.dubbo.netty.client.discovery;

import com.gupao.dubbo.netty.client.loadbalance.LoadbalanceImpl;
import com.gupao.dubbo.netty.server.register.ZKConfig;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.List;

public class DiscoveryImpl implements IDiscovery {
    private final CuratorFramework curatorFramework;
    private LoadbalanceImpl loadbalance = new LoadbalanceImpl();

    {
        curatorFramework = CuratorFrameworkFactory.builder().connectString(ZKConfig.ZK_CONNECTOR_STR).sessionTimeoutMs(4000).retryPolicy(new ExponentialBackoffRetry(1000, 10)).build();
        curatorFramework.start();
    }


    public String discovery(String serviceName) {
        String servicePath = ZKConfig.REGISTOR_PATH + "/" + serviceName;

        try {
            List<String> repos = curatorFramework.getChildren().forPath(servicePath);

            if (repos.size() > 0) {
                return loadbalance.loadbalance(repos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
